package Web;

import Bean.Book;
import Bean.Page;
import Bean.User;
import Utils.WebUtils;
import service.BookService;
import service.BookServiceImpl;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author jianjun
 * @Describe
 * @creat 2021-12-21-16:22
 */
public class LoginAndRegistServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    private BookService bookService = new BookServiceImpl();

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取请求参数pageNo
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        //2. 调用 BookService.page(pageNo,pageSize):page对象
        Page page = bookService.page(pageNo, 4);
        page.setUrl("loginAndRegistServlet?action=page");
        //3.保存 page 对象到 Request 域中
        request.setAttribute("page", page);
        //4. 请求转发到 pages/manager/book_manager.jsp 页面
        request.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(request, response);
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 获取请求参数 --> 封装成Book对象
        String id = request.getParameter("id");
        Book book = WebUtils.copyToBean(request.getParameterMap(), new Book());
        book.setId(Integer.parseInt(id));
        //2 调用BookService.updateBook(book)修改图书
        bookService.updateBook(book);
        //3 重定向回到图书列表管理页面   /工程名/loginAndRegistServlet?action=queryBook
        response.sendRedirect(request.getContextPath() + "/loginAndRegistServlet?action=page&pageNo=" + request.getParameter("pageNo"));
    }

    protected void getBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数 id
        String id = request.getParameter("id");
        //2. 调用 bookService.queryBookById 查询图书
        Book book = bookService.queryBookById(Integer.parseInt(id));
        //3. 保存图书对象到 Request 域中
        request.setAttribute("book", book);
        //4. 请求转发到  /pages/manager/book_edit.jsp 页面
        request.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(request, response);
    }

    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数 id
        String id = request.getParameter("id");
        //2 调用bookService.deleteBookById()，删除图书
        bookService.deleteBook(Integer.parseInt(id));
        //3 重定向回到图书列表管理页面   /工程名/loginAndRegistServlet?action=queryBook
        response.sendRedirect(request.getContextPath() + "/loginAndRegistServlet?action=page&pageNo=" + request.getParameter("pageNo"));
    }

    protected void queryBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 通过 BookService 查询全部图书
        List<Book> bookList = bookService.query();
        //2 把全部图书保存到 Request 域中
        request.setAttribute("bookList", bookList);
        //3 请求转发到 /pages/manager/book_manager.jsp 页面
        request.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(request, response);
    }

    protected void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 获取请求参数 --> 封装成Book对象
        //调用的是外部导入的包的封装方法
        Book book = WebUtils.copyToBean(request.getParameterMap(), new Book());
        //2 调用BookService.addBook()保存图书
        bookService.addBook(book);
        //跳到图书列表页面，如果使用请求转发会有bug
        //在book_manager页面按下f5刷新，会再次添加图书
//        request.getRequestDispatcher("/loginAndRegistServlet?action=queryBook").forward(request, response);
        //使用重定向能够解决上述bug
        //本质是，重新发起了一个请求
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        pageNo += 1;
        response.sendRedirect(request.getContextPath() + "/loginAndRegistServlet?action=page&pageNo=" + pageNo);
    }

    //注销
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 销毁session中用户登录的信息
        request.getSession().invalidate();
        //2. 重定向到首页（或到登录页面）
        response.sendRedirect(request.getContextPath());
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(null, username, password, null);
        User login = userService.login(user);
        //2.验证用户名密码是否存在
        if (login != null) {
            //存在，跳转登录成功页面
            request.getSession().setAttribute("user", login);
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response);
        } else {
            //表单错误，参数回显
            request.setAttribute("msg", "用户名或密码错误");
            request.setAttribute("username", username);
            //不存在，跳回登录界面
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }
    }

    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        User user = WebUtils.copyToBean(request.getParameterMap(), new User());
        //获取自动生成的验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //将验证码移除
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        request.setAttribute("user", user);
        //2.检查验证码是否正确
        if (token != null && token.equals(code)) {
            //3.检查用户名是否可用
            if (!userService.existsUsername(username)) {
                //可用,调用Service保存到数据库
                userService.registUser(new User(null, username, password, email));
                //跳到注册成功页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
            } else {
                System.out.println("用户名已存在");
                //表单错误，参数回显
                request.setAttribute("msg", "用户名已存在");
                request.setAttribute("username", username);
                request.setAttribute("email", email);
                //不可用，跳转回注册页面
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
            }
        } else {
            System.out.println("验证码错误");
            //表单错误，参数回显
            request.setAttribute("msg", "验证码错误");
            request.setAttribute("username", username);
            request.setAttribute("email", email);
            //不正确，跳回注册页面
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
        }
    }
}
